# 载入原始数据 ----
library('dplyr')
library('arules')
library('arulesViz')
library('arulesSequences')


setwd('/Users/lz/Documents/Rlz')
foshan <- read.csv('fs_ft_7day_tag_ch.csv',sep = '|', header =F)
#dplyr
foshan_fixed <- foshan %>%  select(V1,V4)


foshan_apri_trans <- as(strsplit(foshan_fixed$V4,','),'transactions')


# EDA ----
## Apriori ---- 
#jinzhou_call_clean_apri <- jinzhou_call_clean %>%
#  distinct(姓名,联系号码) %>%
#  mutate_if(sapply(.,is.character),as.factor)

# 针对姓名挑选联系人号码，首先去重，其次标准化，最后按照姓名分组，需要联系人号码标准化
# 总共186个主叫用户
jinzhou_call_apri <- foshan_fixed %>%  distinct(V1,V4) 

# 可以先考察是否为整型，%>%  filter(is.numeric(c(联系号码)))
#因为读入可能默认为整型的所以需要转化为字符型
jinzhou_call_apri['联系号码']=as.character(jinzhou_call_apri$联系号码)

#规则化，去除小于11位的同时以1开头，去除10086
jinzhou_call_apri<-jinzhou_call_apri%>%filter(nchar(c(联系号码))>=11,substr(联系号码,1,1)=='1', 联系号码!='10086')


write.csv(as(jinzhou_call_apri, "data.frame"), "jinzhou_modified.csv")


# 按照主叫姓名聚合，同时使用，拼接在一起
jinzhou_call_apri<-jinzhou_call_apri%>%  group_by(手机号码) %>%  summarise(联系号码=paste(联系号码,collapse = ',')) 


# 一下为实验内容
#df <- tibble(x = c(1, 2), y = c("adsf,asdfasd", "basdfsdf"))
#df%>%filter(nchar(c(y))>=9)
#df <- tibble(x = c(1, 2), y = c('1sdf', 2))
#df%>%filter(nchar(c(y))>=2)
#student<-data.frame(ID=c(11,12,13),Name=c("Devin","Edward","Wenli"),Gender=c("M","M","F"))
#data.frame(a=jinzhou_call_apri$联系号码)
#apply(df['x'],0,character())
#df<-as.character(jinzhou_call_apri$联系号码)



#对主叫用户的186个呼叫用户提取作为事务，
jinzhou_call_apri_trans <- as(strsplit(jinzhou_call_apri$联系号码,','),'transactions')
# supp=184*0.03=5.52
jinzou_apriori<- apriori(jinzhou_call_apri_trans,parameter = list(supp=0.03,conf=0.8))
summary(jinzou_apriori)
inspect(jinzou_apriori)

plot(density(size(jinzhou_call_apri_trans)))
plot(jinzou_apriori,method='graph')
plot(jinzou_apriori,method='paracoord')


jinzou_apriori<- apriori(jinzhou_call_apri_trans,parameter = list(supp=0.03,conf=0.8))


order_rules=sort(jinzou_apriori, by='lift')

order_rules1=order_rules[1:10]

plot(order_rules1,method='graph')
plot(order_rules1,method='paracoord')

write.csv(as(order_rules1, "data.frame"), "jinzhou_res_top10rules.csv")




jinzou_apriori<- apriori(jinzhou_call_apri_trans,parameter = list(supp=0,conf=0.8))

summary(jinzou_apriori)
inspect(jinzou_apriori)

plot(density(size(jinzhou_call_apri_trans)))
plot(jinzou_apriori,method='graph')
plot(jinzou_apriori,method='paracoord')




